/**
 * 书籍评论
 */

const { Sequelize, Model } = require('sequelize')
const { sequelize } = require('@core/db.js')
const { ArtNotExistException } = require('@core/http-exception.js')
const { Book } = require('@model/book.js')

class BookComment extends Model {
  // 增加评论
  static async addComment (bookId, content) {
    const book = await Book.findOne({
      where: {
        id: bookId
      }
    })
    if (!book) {
      throw new ArtNotExistException('查不到这个数据')
    }
    let bookComment = await BookComment.findOne({
      where: {
        bookId,
        content
      }
    })
    if (!bookComment) {
      bookComment = await BookComment.create({
        bookId,
        content
      })
    }
    await bookComment.increment('nums', {
      by: 1
    })
  }
  // 短评列表
  static async getCommentList (bookId) {
    const commentList = await BookComment.findAll({
      where: {
        bookId
      }
    })
    return commentList
  }
}

BookComment.init({
  bookId: Sequelize.STRING,
  content: Sequelize.STRING,
  nums: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  }
}, {
  sequelize,
  tableName: 'comment'
})

module.exports = {
  BookComment
}